package lab03.test03;

import java.io.*;

public class Test03 {
    public static void main(String[] args) {
        String path = "F:\\test.txt";
        File myFile = new File(path);
        //创建新文件
        try {
            myFile.createNewFile();
            System.out.println("创建文件成功.");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //通过字节输出流写入内容
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(path);
            fileOutputStream.write(new String("Beijing欢迎你!").getBytes());

            /*String s = "kdsjfkasjdkfajdskf";
            byte[] bytes = s.getBytes();
            fileOutputStream.write(bytes);*/ //将一个byte型的字符串转换为一个byte型的数组。,等价于第二十行。

            System.out.println("写入文件成功.");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //运用数据输入流获取内容
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(path);
            byte[] data = new byte[fileInputStream.available()];    //新建一个字节数组

            while (fileInputStream.read(data) != -1) {
                String s = new String(data);
                System.out.println(s);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //在已有文件中写入内容

        path = "F:\\Hello.txt";
        FileOutputStream file = null;
        try {
            file = new FileOutputStream(path);
            file.write(new String("我的学号是：你自己的学号").getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                file.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //myFile.delete();
    }
}
